package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.exception.UpdateSetmealFailedException;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ttao
 * @since 2023/4/23 11:34
 */

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    /**
     * 根据分类查询套餐数量
     *
     * @param categoryId
     * @return
     */
    @Override
    public Integer countByCategoryId(Long categoryId) {
        return setmealMapper.countByCategoryId(categoryId);
    }

    /**
     * 套餐管理分页条件查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        // 设置分页条件
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.queryPage(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 添加套餐
     *
     * @param setmealDTO
     * @return
     */
    @Override
    @Transactional
    public int saveWithDish(SetmealDTO setmealDTO) {
        // 组装setmeal对象
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        // 套餐表插入数据
        int row = setmealMapper.insert(setmeal);

        // 套餐表数据拿到主键id
        Long setmealId = setmeal.getId();

        // 主键id赋值给setmealDishes 的setmealId 后，在往setmeal_dish表中插入数据
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        // 菜品套餐表中插入数据
        setmealDishService.insertBatch(setmealDishList);
        return row;
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteByIds(List<Long> ids) {
        // 非空校验
        if (ids == null || ids.size() == 0) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_SELECT_FAILED);
        }
        // 判断套餐状态是否启售
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.selectById(id);
            Integer status = setmeal.getStatus();
            if (status.equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        // 删除套餐
        setmealMapper.deleteByIds(ids);
        return 1;

        // 查询出套餐关联的菜品id集合
        /*
        List<Long> dishIds = setmealDishService.selectBySetmealIds(ids);
        if (dishIds != null && dishIds.size() > 0) {
            // 当前套餐关联了菜品
            for (Long dishId : dishIds) {
                // 判断菜品的状态，存在启售的菜品则不能删除
                Dish dish = dishService.selectById(dishId);
                Integer status = dish.getStatus();
                if (status.equals(StatusConstant.ENABLE)) {
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_BE_RELATED_BY_DISH_ENABLE);
                }
            }
        }
         */

    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO selectByIdWithDish(Long id) {
        // 根据id查询套餐数据
        Setmeal setmeal = setmealMapper.selectById(id);

        //  根据id查询套餐和菜品的关联关系
        List<SetmealDish> setmealDishList = setmealDishService.selectById(id);
        // 过滤出起售状态下的菜品和套餐的关联关系
        // List<SetmealDish> setmealDishes = setmealDishList.stream().filter(setmealDish -> {
        //     Dish dish = dishService.selectById(setmealDish.getDishId());
        //     return dish.getStatus().equals(StatusConstant.ENABLE);
        // }).collect(Collectors.toList());

        // 将查询到的数据封装到VO
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishList);
        return setmealVO;
    }

    /**
     * 更新套餐
     *
     * @param setmealVO
     * @return
     */
    @Override
    @Transactional
    public int updateById(SetmealVO setmealVO) {
        // if (StatusConstant.ENABLE.equals(setmealVO.getStatus())) {
        //     // 起售的套餐
        //     for (SetmealDish setmealDish : setmealDishList) {
        //         Dish dish = dishService.selectById(setmealDish.getDishId());
        //         if (dish.getStatus() == StatusConstant.DISABLE) {
        //             throw new UpdateSetmealFailedException(MessageConstant.SETMEAL_UPDATE_FAILED);
        //         }
        //     }
        // }

        // 组装对象
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealVO, setmeal);

        // 更新套餐表
        setmealMapper.updateById(setmeal);

        // 更新套餐菜品关系表

        // 获取套餐菜品关联关系
        List<SetmealDish> setmealDishList = setmealVO.getSetmealDishes();

        // 获取套餐id
        Long setmealId = setmealVO.getId();
        setmealDishList.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        // 删除之前套餐菜品关联关系
        setmealDishService.deleteBySetmealId(setmealId);

        // 插入新的套餐菜品关联关系
        return setmealDishService.insertBatch(setmealDishList);
    }

    /**
     * 启用、禁用菜品
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public int startOrStop(Integer status, Long id) {
        // 构建套餐对象
        Setmeal setmeal = Setmeal.builder()
                .status(status)
                .id(id)
                .build();
        if (!status.equals(StatusConstant.DISABLE)) {
            // 套餐起售
            // 根据套餐id查询菜品的起售状态 SETMEAL_ENABLE_FAILED = "套餐内包含未启售菜品，无法启售";
            List<Long> setmealIds = new ArrayList<>();
            setmealIds.add(id);
            List<Long> dishIds = setmealDishService.selectBySetmealIds(setmealIds);
            // 根据菜品id集合查询菜品数据
            for (Long dishId : dishIds) {
                Dish dish = dishService.selectById(dishId);
                Integer dishStatus = dish.getStatus();
                if (dishStatus.equals(StatusConstant.DISABLE)) {
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            }
        }
        return setmealMapper.updateById(setmeal);
    }

    /**
     * 根据分类id查询套餐
     *
     * @param setmeal
     * @return
     */
    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        return setmealMapper.list(setmeal);
    }

    /**
     * 根据套餐id查询包含的菜品列表
     *
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> selectDishItemById(Long id) {
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(StatusConstant.ENABLE);
        return setmealMapper.selectDishItemById(setmeal);
    }

    /**
     * 根据id查询套餐数据
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal selectById(Long id) {
        return setmealMapper.selectById(id);
    }
}
